package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 108. 将有序数组转换为二叉搜索树
 * @date 2025/3/24 11:15
 */
public class E108 {

    /**
     * <h3>方法一：递归</h3>
     *
     * @param nums 有序数组
     * @return 二叉搜索树
     */
    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST(nums, 0, nums.length - 1);
    }

    /**
     * 递归
     *
     * @param nums  有序数组
     * @param left  左边界
     * @param right 右边界
     * @return 二叉搜索树
     */
    public TreeNode sortedArrayToBST(int[] nums, int left, int right) {
        if (left > right) return null;
        int median = (left + right) >> 1;
        TreeNode root = new TreeNode(nums[median]);
        root.left = sortedArrayToBST(nums, left, median - 1);
        root.right = sortedArrayToBST(nums, median + 1, right);
        return root;
    }
}
